// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../components/Home.vue';
import Login from '../components/Login.vue';
import Register from '../components/Register.vue';
import UserHome from '../views/UserHome.vue';
import CourierHome from '../views/CourierHome.vue';
import StuffHome from '../views/StuffHome.vue';
import AdminHome from '../views/AdminHome.vue';
import store from '../store';

const routes = [
  { path: '/', component: Home },
  { path: '/login', component: Login },
  { path: '/signup', component: Register },
  { 
    path: '/info',
    component: Home,
    meta: { requiresAuth: true }
  },
  { 
    path: '/user',
    component: UserHome,
    meta: { requiresAuth: true, role: 'User' }
  },
  { 
    path: '/courier',
    component: CourierHome,
    meta: { requiresAuth: true, role: 'Courier' }
  },
  { 
    path: '/stuff',
    component: StuffHome,
    meta: { requiresAuth: true, role: 'Stuff' }
  },
  { 
    path: '/admin',
    component: AdminHome,
    meta: { requiresAuth: true, role: 'Admin' }
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.state.isAuthenticated) {
      next('/login');
    } else {
      const userRole = store.state.role;
      if (to.meta.role && to.meta.role !== userRole) {
        next('/info');
      } else {
        next();
      }
    }
  } else {
    next();
  }
});

export default router;
